Max value using NOT bitwise operator#1480
Conversation
There was a problem hiding this comment.
Pull request overview
Updates the Grains “Introduction” approach snippet to compute the uint64_t maximum (total grains) using the bitwise NOT operator instead of a shift/subtract expression.
Changes:
- Replaces the
total()return expression with~0ULL. - Adds explanatory comments describing bitwise NOT and the all-ones bit pattern.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // '~' is the NOT bitwise operator in C | ||
| // By flipping all bits of 0 in a uint64_t container (000...0 -> 111...1) | ||
| // Can you guess what it returns? | ||
| return ~0ULL; |
There was a problem hiding this comment.
Came to say this. Doing this correctly is more involved than the current solution (and the sample solution provided is not meant to be "optimal", just good).
There was a problem hiding this comment.
@ryanplusplus This is a PR for the "Bit-shifting" approach in the "Dig Deeper" section that Bobahop wrote (https://exercism.org/tracks/c/exercises/grains/dig_deeper), not the example solution.
| // '~' is the NOT bitwise operator in C | ||
| // By flipping all bits of 0 in a uint64_t container (000...0 -> 111...1) | ||
| // Can you guess what it returns? | ||
| return ~0ULL; |
|
@Aercwarden The Dig Deeper section is meant to present a variety of different approaches. Currently there's only one, labeled "Bit-shifting", that shows how you can calculate the result via bit-shifting. Changing the implementation of You could write a new approach and maybe call it "Bit-flipping". I guess the maintainers of this track would welcome such a contribution. BTW: return 18446744073709551615;
return 0xFFFFFFFFFFFFFFFF;
return (1ULL << 63) * 2 - 1;
return (1ULL << 32 << 32) - 1;
return (2ULL << 63) - 1;
return UINT64_MAX;
return ~UINT64_C(0);
return UINT64_C(-1);
return 2 * square(64) - 1;and because the return type is return ULLONG_MAX;
return -1;With optimizations turned on the compiler will generate the same instructions for all of them, see the Compiler Explorer. So there's a lot of different approaches that could be described similar to the one called "Bit-shifting". |
|
Thanks for the advice @siebenschlaefer |
No description provided.